package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Slf4j
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    private final OrderFeignClient orderFeignClient;
    private final AccountFeignClient accountFeignClient;

    public PaymentInfoServiceImpl(OrderFeignClient orderFeignClient, AccountFeignClient accountFeignClient) {
        this.orderFeignClient = orderFeignClient;
        this.accountFeignClient = accountFeignClient;
    }

    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo, Long userId) {
        PaymentInfo paymentInfo = this.baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        // 如果支付信息存在数据库则返回
        if (paymentInfo != null) {
            log.debug("订单号{}的支付信息已存在", orderNo);
            return paymentInfo;
        }
        // 创建支付信息对象
        paymentInfo = new PaymentInfo();
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WEIXIN);
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            // 远程订单服务获取订单信息
            Result<OrderInfo> orderInfoResult = this.orderFeignClient.getOrderInfo(orderNo);
            if (Result.FAIL == orderInfoResult.getCode()) {
                throw new GuiguException(ResultCodeEnum.REMOTE_ERROR);
            }
            OrderInfo orderInfo = orderInfoResult.getData();
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
                throw new GuiguException(ResultCodeEnum.ORDER_STATUS_ERROR);
            }
            // 封装支付金额和交易内容
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
        }
        // 保存本地交易记录且返回
        this.save(paymentInfo);
        return paymentInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaymentInfoSuccess(Transaction transaction) {
        // 1.根据订单编号查询本地交易记录状态
        String orderNo = transaction.getOutTradeNo();
        PaymentInfo paymentInfo = this.baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        if (paymentInfo == null) {
            throw new GuiguException(ResultCodeEnum.TRANSACTION_NOT_FOUND);
        }
        // 如果已支付：返回即可
        if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentInfo.getPaymentStatus())) {
            return;
        }

        // 2.更新本地交易记录
        // 2.1 本地交易记录关联微信支付交易ID
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        // 2.2 更新回调时间，及回调内容
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        // 2.3 更新交易状态为已支付
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        this.updateById(paymentInfo);

        //3.远程调用订单服务/账户服务 完成订单/充值状态变更：已支付
        //3.1 支付类型为1301-订单
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentInfo.getPaymentType())) {
            Result<Void> result = this.orderFeignClient.updateOrderOnPaySuccess(orderNo);
            if (Result.FAIL == result.getCode()) {
                throw new GuiguException(500, "远程修改订单异常：" + orderNo);
            }
        }

        //3.2 支付类型为1302-充值
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentInfo.getPaymentType())) {
            Result<Void> result = this.accountFeignClient.updateAccountOnPaySuccess(orderNo);
            if (Result.FAIL == result.getCode()) {
                throw new GuiguException(500, "远程修改账户异常：" + orderNo);
            }
        }
    }
}
